import json

'''
with open (r'./in_theaters.json','r') as f:
    load = json.load(f)
for item in load["subjects"]:
    sss = []
    for i in item["casts"]:#演员 actor
        sss.append(i["name"])
    EMP(id=None,h_name=item["title"],grade=item["rating"]["average"],director=item["directors"][0]["name"],actor=str(sss),genres=str(item["genres"]),pubdates=item["pubdates"],durations=item["durations"])
    
# item = load["subjects"][0]

print(item["title"])#h_name
print(item["rating"]["average"])#评分 grade
print(item["directors"][0]["name"])#导演 director

actor = []
for i in item["casts"]:#演员 actor
    actor.append(i["name"])
print(actor)


print(item["genres"])#类型 genres
print(item["pubdates"])#上映日期 pubdates
print(item["durations"])#片长 durations
'''


from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import Column,  Integer, String, FLOAT

Base = declarative_base()
class EMP(Base):
    __tablename__ = 'hot_showing'

    id = Column(Integer,primary_key=True, autoincrement=True, nullable=True)
    h_name = Column(String(20))
    grade = Column(FLOAT(1,1))
    director = Column(String(225))
    actor = Column(String(225))
    genres = Column(String(225))
    pubdates = Column(String(225))
    durations = Column(String(225))

class OrmDB(object):
    def __init__(self, username, password, host, port, dbname):
        sql = 'mysql+pymysql://{0}:{1}@{2}:{3}/{4}?charset=utf8'.format(username, password, host, port, dbname)
        engine = create_engine(sql, max_overflow=5)
        Session = sessionmaker(bind=engine) # 创建一个sessionmark对象
        self.session = Session()  # 创建一个session对象，用来调用内置的增删改查命令

    def addObject(self, obj):
        self.session.add_all(obj)
        self.session.commit()


if __name__ == '__main__':
    with open (r'./in_theaters.json','r') as f:
        load = json.load(f)
    for item in load["subjects"]:
        sss = []
        for i in item["casts"]:#演员 actor
            sss.append(i["name"])
        obj=[EMP(id=None,h_name=item["title"],grade=item["rating"]["average"],director=item["directors"][0]["name"],actor=str(sss),genres=str(item["genres"]),pubdates=str(item["pubdates"]),durations=str(item["durations"]))]
        print(obj)
        db = OrmDB('root', '123456', 'localhost', 3306, 'zuoye')
        db.addObject(obj)

